<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Call\Action\Dashboard;

use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Call\Constants\ClientTypeCode;
use MoChat\App\Call\Logic\RecordIndexLogic;
use MoChat\App\Client\Model\Client;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\Client\Logic\IndexLogic;
use MoChat\App\Sales\Contract\CallRecordContract;
use MoChat\App\Sales\Contract\SalesClientTaskContract;
use MoChat\App\Sales\Model\CallRecord;
use Hyperf\Di\Annotation\Inject;
use MoChat\App\User\Model\User;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 呼叫.
 * @Controller
 */
class CallRequestRecord extends AbstractAction
{
    use ValidateSceneTrait;

    public function buildUniqueId()
    {
        $microtime = microtime();
        $microtime = substr($microtime, strpos($microtime, '.') + 1, 6);
        return date("YmdHis") . $microtime . mt_rand(10000000, 99999999);
    }


    public function replaceUrlDomain($originalUrl)
    {
        if ($originalUrl) {
            $newDomain = env("CALL_CENTER_BASE_URL");
            // 解析原始URL
            $urlParts = parse_url($originalUrl);
            if (!empty($urlParts)) {
                // 构建新的URL
                return  $newDomain.$urlParts['path'];
            }
            return  '';
        }
        return '';

    }


    /**
     * @RequestMapping(path="/dashboard/call/requestRecord", methods="POST")
     */
    public function handle()
    {
        $re = $this->request->all();
        $re["recording_file_url"] = $this->replaceUrlDomain($re["recording_file_url"] ?? '');
        @file_put_contents(BASE_PATH . '/public/' . date('Ymd') . '.txt', json_encode($re, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL, FILE_APPEND);
        try {
            $extn = Db::table('user')->where('phone', $re["caller_id_number"])->value('extn');
            $over_time = ((int)(strtotime($re['over_time'])));
            $answered_time = ((int)strtotime($re["answered_time"])) ?? 0;
            $time = 0;
            if ($over_time && $answered_time) {
                $time = $over_time - $answered_time;
            }
            if (!empty($re["recording_file_url"])){
                $re["recording_file_url"] = env("CALL_CENTER_BASE_URL_VIDEO").parse_url($re["recording_file_url"])['path'];
            }
            Db::table('call_record')->insert(
                [
                    "callaccept" => $re['call_accept'],
                    "caller_id_name" => $extn ?? $re["caller_id_name"],
                    "caller_id_number" => $extn ?? $re["caller_id_number"],
                    "destination_number" => $re["destination_number"] ?? null,
                    "created_time" => $re["created_time"] ?? null,
                    "answered_time" => $re["answered_time"] ?? "",
                    "ivr_dtmf" => $re["ivr_dtmf"] ?? "",
                    "business_type" => $re["business_type"] ?? "",
                    "over_time" => $re["over_time"] ?? null,
                    "status" => 0,
                    "gateway" => $re["gateway"] ?? "",
                    "batch_accept" => $re["batch_accept"] ?? "",
                    "reday" => $re["created_time"] ? $re["created_time"] : null,
                    "hangup_side" => $re["hangup_side"] ?? "",
                    "year" => $re["created_time"] ? date('Y', strtotime($re["created_time"])) : null,
                    "month" => $re["created_time"] ? date('m', strtotime($re["created_time"])) : null,
                    "record_url" => $re["recording_file_url"] ?? "",
                    "call_type" => $re['call_direction'],
                    "wait_duration" => isset($re["beginRingTime"]) && isset($re['endRingTime']) ? strtotime($re["endRingTime"]) - strtotime($re['beginRingTime']) : 0,
                    "call_duration" => $time,
                    "other_str" => $re["other_str"] ?? "",
                    "trans_number" => $re["Bind_number"] ?? "",
                    "other_accept" => $re["other_accept"] ?? "",
                    "deal_result" => $re["deal_result"] ?? "",
                    "da_similarity" => $re["da_similarity"] ?? "",
                    "da_ar" => $re["da_ar"] ?? "",
                    "da_type" => $re["da_type"] ?? "",
                    "queue_uuid" => $re["queue_uuid"] ?? "",
                    "user_uuid" => $re["user_uuid"] ?? "",
                    "dtmf" => $re["dtmf"] ?? "",
                    "type" => 1
                ]
            );
        } catch (\Exception $exception) {
            @file_put_contents(BASE_PATH . '/public/error_' . date("Ymd") . '.txt', $exception->getMessage() . PHP_EOL, FILE_APPEND);
        }
        throw new CommonException(200, 'success');
        return [];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
        ];
    }
}
